<template>
  <el-dialog
    v-model="dialogVisable"
    title="修改组织架构"
    :append-to-body="true"
    @close="closeDialog"
    :destroy-on-close="true"
    width="600"
  >
    <el-form
      :model="editOrgForm"
      :rules="editOrgFormrules"
      ref="editOrgFormRef"
      label-width="100px"
    >
      <el-form-item label="所属父组织" label-width="100px">
        <el-tree-select
          v-model="editOrgForm.parentId"
          node-key="id"
          default-expand-all
          :props="treeProps"
          :data="orgTree"
          check-strictly
        />
      </el-form-item>
      <el-form-item label="组织名称" prop="displayName">
        <el-input v-model="editOrgForm.displayName" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div class="modal-footer">
      <el-button type="primary" @click="saveOrg">保存</el-button>
    </div>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  updateOrganization,
  getOrganizationunitForTree,
  moveOrganization,
} from "@/api/identity/organizationUnits/index";
import { FormInstance } from "element-plus";
const props = defineProps({
  currentNode: { type: Object, default: null },
});
const treeProps = {
  children: "child",
  label: "displayName",
};
const editOrgFormRef = ref<FormInstance>();
const editOrgForm = ref<any>({});
const editOrgFormrules = ref<FormRules>({
  displayName: [{ required: true, message: "请输入组织架构名称", trigger: "blur" }],
});
const orgTree = ref<any>([]);
const dialogVisable = ref<boolean>(true);


const emit = defineEmits(["closedialogevent", "refresh"]);
const saveOrg = () => {
  editOrgFormRef.value?.validate((valid) => {
    if (valid) {
      let param = {
        id: props.currentNode.data.id,
        displayName: editOrgForm.value.displayName,
        parentId: editOrgForm.value.parentId,
      };
      updateOrganization(param).then((res) => {
        if (res) {
          moveOrganization(param).then((movRes) => {
            ElNotification({
              title: "提示",
              message: "修改组织架构成功",
              type: "success",
              duration: 2000,
            });
            closeDialog();
            emit("refresh");
          });
        } else {
          return false;
        }
      });
    }
  });
};
const closeDialog = () => {
  dialogVisable.value = false;
  emit("closedialogevent", dialogVisable.value);
};
onMounted(async () => {
  orgTree.value = await getOrganizationunitForTree({});
  //currentOrg.value = await getOrganization(props.currentId);
  //console.log("currentOrg", props.currentNode);
  editOrgForm.value.displayName = props.currentNode.data.displayName;
  editOrgForm.value.parentId = props.currentNode.data.parentId;
});
</script>
